<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>智能简历爬取系统</title>
		<link rel="stylesheet" href="/static/style.css">
	</head>
	<body>
		<div class="container">
			<h1>📝 智能简历爬取系统</h1>

			<div class="input-area">
				<h3>🔗 输入简历URL</h3>
				<textarea id="urlInput"
					placeholder="每行输入一个简历URL&#10;例如：&#10;http://example.com/resume1&#10;http://example.com/resume2"></textarea>

				<div class="settings">
					<label>并发数量：</label>
					<select id="workerSelect">
						<option value="1">保守模式 (1个)</option>
						<option value="3" selected>标准模式 (3个)</option>
						<option value="5">快速模式 (5个)</option>
						<option value="10">极速模式 (10个)</option>
					</select>
				</div>

				<button id="startBtn">🚀 开始爬取</button>
			</div>

			<div class="result-area" id="resultArea" style="display:none;">
				<h3>📊 爬取结果</h3>
				<div class="progress-container">
					<progress id="progressBar" value="0" max="100"></progress>
					<div id="statusText">准备开始...</div>
				</div>

				<div class="stats" id="stats"></div>

				<button id="downloadBtn" class="download-btn">💾 下载Excel</button>
			</div>
		</div>

		<script>
			const startBtn = document.getElementById('startBtn');
			const downloadBtn = document.getElementById('downloadBtn');
			const resultArea = document.getElementById('resultArea');
			const progressBar = document.getElementById('progressBar');
			const statusText = document.getElementById('statusText');
			const statsDiv = document.getElementById('stats');

			let currentTaskId = null;

			// 增强版的开始爬取处理
			startBtn.addEventListener('click', async () => {
				const rawUrls = document.getElementById('urlInput').value.trim();
				const workers = document.getElementById('workerSelect').value;

				// 处理URL输入
				const urls = rawUrls.split('\n')
					.map(url => url.trim())
					.filter(url => url.length > 0);

				if (urls.length === 0) {
					alert('请输入至少一个有效的URL');
					return;
				}

				// 验证URL格式
				const invalidUrls = urls.filter(url => {
					try {
						new URL(url);
						return false;
					} catch {
						return true;
					}
				});

				if (invalidUrls.length > 0) {
					alert(`以下URL格式无效:\n${invalidUrls.join('\n')}`);
					return;
				}

				// 初始化UI状态
				startBtn.disabled = true;
				resultArea.style.display = 'block';
				progressBar.value = 0;
				statusText.textContent = '正在提交任务...';
				statsDiv.innerHTML = '';

				try {
					const response = await fetch('/api/start', {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'Accept': 'application/json'
						},
						body: JSON.stringify({
							urls: urls,
							workers: workers
						})
					});

					// 处理非成功响应
					if (!response.ok) {
						const errorData = await response.json().catch(() => ({}));
						throw new Error(
							errorData.error ||
							errorData.message ||
							`服务器错误: ${response.status}`
						);
					}

					const data = await response.json();

					// 验证响应数据
					if (!data.task_id) {
						throw new Error('服务器返回无效的任务ID');
					}

					currentTaskId = data.task_id;
					checkProgress();

				} catch (error) {
					let errorMessage = error.message;

					// 处理包含HTML的错误响应
					if (errorMessage.includes('<') || errorMessage.includes('DOCTYPE')) {
						errorMessage = '服务器返回了无效响应，请检查后端服务是否正常运行';
					}

					statusText.textContent = `错误: ${errorMessage}`;
					progressBar.value = 0;
					startBtn.disabled = false;

					console.error('爬取请求失败:', error);
				}
			});

			// 改进的任务状态检查
			async function checkProgress() {
				try {
					const response = await fetch(`/api/status/${currentTaskId}`);

					if (!response.ok) {
						throw new Error('状态检查失败');
					}

					const data = await response.json();

					// 处理不同任务状态
					switch (data.status) {
						case 'running':
							progressBar.value = 50;
							statusText.textContent = '正在爬取中...';
							setTimeout(checkProgress, 2000);
							break;

						case 'completed':
							progressBar.value = 100;
							statusText.textContent = '爬取完成！';
							statsDiv.innerHTML = `
                            <p>总计: ${data.stats.total} 份简历</p>
                            <p>成功: <span class="success">${data.stats.success}</span></p>
                            <p>失败: <span class="error">${data.stats.total - data.stats.success}</span></p>
                            ${data.stats.failedUrls ? `<p>失败URL: <br>${data.stats.failedUrls.join('<br>')}</p>` : ''}
                        `;
							startBtn.disabled = false;
							break;

						case 'error':
							throw new Error(data.message || '任务执行失败');

						default:
							throw new Error('未知任务状态');
					}
				} catch (error) {
					statusText.textContent = `状态检查错误: ${error.message}`;
					progressBar.value = 0;
					startBtn.disabled = false;
					console.error('进度检查失败:', error);
				}
			}

			// 增强的文件下载处理
			downloadBtn.addEventListener('click', async () => {
				if (!currentTaskId) {
					alert('没有可下载的任务');
					return;
				}

				downloadBtn.disabled = true;
				statusText.textContent = '准备下载文件...';

				try {
					const response = await fetch(`/api/download/${currentTaskId}`);

					if (!response.ok) {
						const errorData = await response.json().catch(() => ({}));
						throw new Error(
							errorData.error ||
							errorData.message ||
							`下载失败: ${response.status}`
						);
					}

					// 使用Blob API处理下载
					const blob = await response.blob();
					const url = window.URL.createObjectURL(blob);
					const a = document.createElement('a');
					a.href = url;
					a.download = `resume_data_${currentTaskId.slice(0, 8)}.xlsx`;
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a);
					window.URL.revokeObjectURL(url);

					statusText.textContent = '下载完成！';
				} catch (error) {
					statusText.textContent = `下载错误: ${error.message}`;
					console.error('下载失败:', error);
				} finally {
					downloadBtn.disabled = false;
				}
			});
		</script>
	</body>
</html>